<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="单位名称" prop="randomUnitName">
        <el-input
          v-model="queryParams.randomUnitName"
          placeholder="请输入单位名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['unit:extract:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['unit:extract:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['unit:extract:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="extractList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column
        label="申请单位"
        align="left"
        prop="createBy"
        show-overflow-tooltip
      />
      <el-table-column
        label="单位库"
        align="left"
        prop="randomUnitTypeName"
        show-overflow-tooltip
      />
      <el-table-column
        label="单位名称"
        align="left"
        prop="randomUnitName"
        show-overflow-tooltip
      />
      <el-table-column
        label="处罚时间(月)"
        align="left"
        prop="randomMonth"
        width="150"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['unit:extract:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['unit:extract:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目申请对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="125px"
        size="mini"
      >
        <el-row>
          <el-row :gutter="15">
            <el-col
              :span="12"
              style="padding-top: -20px; padding-bottom: -50px"
            >
              <el-form-item label="申请单位" prop="createBy">{{
                form.createBy
              }}</el-form-item>
            </el-col>
            <el-col
              :span="12"
              style="padding-top: -20px; padding-bottom: -50px"
            >
              <el-form-item label="关联项目" prop="extractItem">
                <div class="custom-input">
                  <el-input :value="form.extractItem" @click.native="relatedVisible = true" readonly/>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="处罚时间" prop="randomMonth">
                <el-date-picker
                  v-model="form.randomMonth"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="处罚理由" prop="randomBanRansom">
            <el-input
              v-model="form.randomBanRansom"
              type="textarea"
              placeholder="请输入处罚理由"
            />
          </el-form-item>
        </el-row>
        <el-form-item label="上传附件" label-width="130px" prop="randomUrl">
          <el-upload
            class="upload-demo other"
            :disabled="uploadDisabled"
            :accept="acceptType"
            ref="uploadFile"
            action=""
            :show-file-list="false"
            :http-request="uploadFile"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              请上传bmp，gif，jpg，jpeg，png文件，且不超过10MB
            </div>
          </el-upload>

          <div class="image-wrap" v-if="imgUrl.length > 0">
            <div
              class="uploadimg-wrap"
              v-for="(item, index) in imgUrl"
              :key="index"
            >
              <el-image
                style="width: 100px; height: 100px"
                :src="item"
                fit="cover"
                :preview-src-list="imgUrl"
                :z-index="3000"
              >
              </el-image>
              <i class="icon el-icon-error" @click="removeImg(index)"></i>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button ref="xx" type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <RealtedPorject :visible.sync="relatedVisible" @getRowId="getRowId"/>
  </div>
</template>

<script>
import {
  listExtract,
  getExtract,
  delExtract,
  addExtract,
  updateExtract,
  exportExtract,
  addBanRandom,
  CheckReason,
  submit,
  Department,
} from "@/api/unit/extract";
import FileUpload from "@/components/FileUpload";
import {
  listUnit,
  randomlist,
  getUnit,
  delUnit,
  addUnit,
  updateUnit,
  exportUnit,
  forbiddenList,
} from "@/api/unit/unit";
import { listUnittype, getUnittype } from "@/api/unit/unittype";
import { listUser } from "@/api/system/user";
import {
  listRandom,
  getRandomMsg,
  DeleteMapping,
  getApplyPunish,
  getRandom,
  updateRandom,
  submitForm,
  getRandomdelete,
  getRandomName
} from "@/api/unit/random";
import service from "../../components/utils/request.js";
import RealtedPorject from "./components/RelatedProjects";

export default {
  name: "ExtractIndex",
  components: {
    FileUpload,
    RealtedPorject
  },
  data() {
    return {
      //打开预览
      innerVisible: false,
      //禁用上传按钮
      uploadDisabled: false,
      //动态控制rowspan
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 附件
      randomUrl: [],
      //抽取人单位字典
      unitTypeponsonOptions: [],
      // 项目申请表格数据
      extractList: [],
      // 单位信息表格数据
      unitList: [],
      // 单位类型字典
      unitTypeOptions: [],
      //单位列表
      unitTypeOptionsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      exclude: false,
      outframe: false,
      unitId: "",
      unittype: "",
      randomUnitName: "",
      Random: {
        randomUnittypeId: null,
        randomBanRansom: null,
        randomUnitId: null,
        randomUnitName: null,
      },
      // 排除项目集合
      RandomList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        randomUnitName: null,
        extractUser: null,
        extractAddress: null,
        extractPrice: null,
        extractApproveStatus: null,
        maxPrice: null,
        randomUnittypeId: null,
        userId: null,
        unitType: null,
        extractId: null,
        randomUnitId: null,
        randomBan: "0",
      },
      QqqqueryParams: {
        randomUnitName: null,
        extractUser: null,
        extractAddress: null,
        extractPrice: null,
        extractApproveStatus: null,
        maxPrice: null,
        randomUnittypeId: null,
        userId: null,
        unitType: null,
      },
      UnitqueryParams: {
        extractId: null,
        unitName: null,
        unitNaturalGrade: null,
        unitNaturalScope: null,
        unitRemarks: null,
        unitType: null,
      },
      // 表单参数
      form: {},
      //单位详情
      formUnit: {},
      randomList: {
        extractId: null,
        randomBanRansom: null,
        randomUnittypeId: null,
        randomUnitName: null,
        randomUnitId: null,
      },
      // 表单校验
      rules: {
        unitName: [
          { required: true, message: "单位不能为空", trigger: "blur" },
        ],
        randomMonth: [
          { required: true, message: "处罚时间不能为空", trigger: "blur" },
        ],
        extractItem: [
          { required: true, message: "请选择关联项目"}
        ],
        randomUrl: [
          { required: true, message: "请上传附件"}
        ]
      },
      // 上传文件的图片地址
      imgUrl: [],
      // 接受的文件类型
      acceptType: "bmp,gif,jpg,jpeg,png",
      // 图片类型
      imageType: "bmp,gif,jpg,jpeg,png",
      relatedVisible: false,
      extracItem: {}
    };
  },
  created() {
    this.getList();
    listUnittype(this.unitTypeParams).then((response) => {
      this.unitTypeOptions = response.rows;
    });
  },
  methods: {
    //else if(row.unitNaturalGrade.length>10){
    //	 return 'success-row';}
    /** 查询项目申请列表 */
    getList() {
      this.loading = true;
      Department(this.queryParams).then((response) => {
        this.queryParams.userId = response.data.userId;
        this.loading = false;
      });
      this.queryParams.randomBan = "6";
      listRandom(this.queryParams).then((response) => {
        this.extractList = response.rows;
        this.unitTypeponsonOptions = response.rows;
        this.total = response.total;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.form.resetFields();
      console.log(this.form);
    },
    //抽取人单位
    UnitTypeChangepenson(value) {
      listUser().then((response) => {
        for (var o = 0; o < response.rows.length; o++) {
          if (value == response.rows[o].userId) {
            this.queryParams.createBy = response.rows[o].nickName;
          }
        }
      });
    },
    // 上传文件，获取文件地址
    async uploadFile(eleFile) {
      // console.log(eleFile)
      const file = eleFile.file;
      console.log(file);
      let fileType = file.type;
      fileType = fileType.split("/");
      fileType = fileType[fileType.length - 1];
      // 判断文件大小
      if (file.size > 10 * 1024 * 1024) {
        this.$message.error("文件大小不能超过10MB");
        return;
      }
      // 判断文件类型
      if (!this.acceptType.includes(fileType)) {
        this.$message.error("文件类型不正确");
        let uid = file.uid;
        let idx = this.$refs.uploadFile.uploadFiles.findIndex(
          (item) => item.id === uid
        );
        this.$refs.uploadFiles.splice(idx, 1);
        return;
      }
      // 判断文件个数
      if (this.imgUrl.length > 2) {
        this.$message.error("最多只能上传三个文件");
        return;
      }
      const fd = new FormData();
      fd.append("file", file);
      try {
        const res = await service.post("/common/upload", fd, {
          headers: { "content-type": "multipart/form-data" },
        });
        if (res.code === 200) {
          // console.log(res)
          const obj = {
            name: file.name,
            url: res.url,
          };
          if (this.imageType.includes(fileType)) {
            this.imgUrl.push(res.url);
          }
          this.form.randomUrl = this.imgUrl;
          // console.log(obj)
          this.$message({
            message: "上传成功",
            type: "success",
          });
        }
      } catch (e) {
        this.$message.error(e);
      }
    },
    closeDialog() {
      this.form.randomUrl = [];
      this.imgUrl = [];
    },
    // 表单重置
    reset() {
      this.form = {
        extractId: null,
        extractApproveStatus: null,
        createBy: null,
        extractPriceUrl: null,
        randomUrl: null,
        unitTypeName: null,
        unitName: null,
        randomBanRansom: null,
        randomUnitId: null,
        randomMonth: null,
        randomUnittypeId: null,
        extractItem: null
      };
      this.resetForm("form");
    },
    //单位详情表单重置
    resetUnit() {
      this.formUnit = {
        unitId: null,
        unitSort: null,
        unitType: null,
        unitName: null,
        unitNaturalGrade: null,
        unitNaturalScope: null,
        unitAddress: null,
        unitRemarks: null,
      };
    },
    // 单位库类型翻译
    unitTypeFormat(row, column) {
      return this.selecttypeLabel(this.unitTypeOptions, row.randomUnittypeId);
    },
    //时间翻译
    createTimeTime(row, column) {
      if (row.createTime.length > 10) {
        return row.createTime.substr(0, 10);
      }
    },
    //转换单位库类型
    selecttypeLabel(datas, value) {
      var actions = [];

      Object.keys(datas).some((key) => {
        if (datas[key].unittypeId == "" + value) {
          actions.push(datas[key].unittypeName);
          return true;
        }
      });
      return actions.join("");
    },
    async UnitTypeChangesou(value) {
      //查询table数据
      this.UnitqueryParams.unitType = value;
      this.UnitqueryParams.extractId = this.form.extractId;
      await randomlist(this.UnitqueryParams).then((response) => {
        this.unitList = response.rows;
        this.loading = false;
      });
      this.QqqqueryParams.unitType = value;
      await forbiddenList(this.QqqqueryParams).then((response) => {
        console.log(response.rows);
        this.unitTypeOptionsList = response.rows;
      });
    },
    //单位选择select改变方法
    UnitTypeunitChange(value, label) {
      this.form.randomUnitId = value;
    },
    //单位库选择select改变方法
    async UnitTypeChange(value) {
      if (this.form.randomUnitName != undefined) {
        this.form.randomUnitName = null;
      }
      //查询table数据
      this.UnitqueryParams.unitType = value;
      this.UnitqueryParams.extractId = this.form.extractId;
      await randomlist(this.UnitqueryParams).then((response) => {
        this.unitList = response.rows;
        this.loading = false;
      });
      this.QqqqueryParams.unitType = value;
      await forbiddenList(this.QqqqueryParams).then((response) => {
        this.unitTypeOptionsList = response.rows;
      });
    },
    //根据单位库类型，查询出对应单位列表
    getRandomList() {
      randomlist(this.UnitqueryParams).then((response) => {
        this.unitList = response.rows;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset();
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.extractId);
      this.names = selection.map((item) => item.randomId);
      this.namesid = selection.map((item) => item.randomUnitName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form.unitName = null;
      Department().then((response) => {
        this.form.createBy = response.data.createBy;
        this.form.userId = response.data.userId;
      });
      this.reset();
      this.unitList = [];
      this.RandomList = [];
      this.open = true;
      this.title = "处罚申请";
      this.uploadDisabled = false;
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      const randomId = row.randomId || this.names;
      await getRandom(randomId).then((response) => {
        response.data.randomMonth = [response.data.startTime, response.data.endTime];
        this.form = {...response.data, extractItem: ""};
        if (response.data.randomUrl) {
          this.imgUrl = response.data.randomUrl.split(",");
        }
        this.title = "修改申请表";
      });
      await getRandomName({extractId: this.form.extractId}).then(res => {
        this.form.extractItem = res.msg;
        this.open = true;
      });
      this.QqqqueryParams.unitType = row.randomUnittypeId;
      await forbiddenList(this.QqqqueryParams).then((response) => {
        this.unitTypeOptionsList = response.rows;
      });
    },
    overcome(row) {
      this.unitId = row.unitId || this.ids;
      this.unittype = row.unitType || this.ids;
      this.unitName = row.unitName || this.ids;
      this.exclude = true;
      this.title = "排除单位";
    },
    /** 提交项目申请按钮 */
    submitForm() {
      if (Array.isArray(this.form.randomUrl)) {
        this.form.randomUrl = this.form.randomUrl.join(",");
      }
      console.log(this.form);
      this.$refs["form"].validate((valid) => {
        const newForm = {...this.form}
        newForm.extractId = this.extracItem.extractId;
        if(newForm.randomMonth > 0) {
          const [startTime, endTime] = newForm.randomMonth;
          newForm.startTime = startTime;
          newForm.endTime = endTime;
        }
        delete newForm.randomMonth;
        if (valid) {
          if (newForm.randomId != null) {
            updateRandom(newForm)
              .then((response) => {
                console.log(response);
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            getApplyPunish(newForm).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    call() {
      this._data.exclude = false;
    },
    reason(row) {
      this.outframe = true;
      this.Random.randomUnitName = this.unitName;
      this.Random.randomUnittypeId = this.unittype;
      this.Random.randomUnitId = this.unitId;
    },
    determined() {
      this._data.outframe = false;
    },
    // confirm(){
    //   this.confirm=false
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const randomId = row.randomId || this.names;
      const randomUnitName = row.randomUnitName || this.namesid;
      this.$confirm(
        '是否确认删除单位名称为"' + randomUnitName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return getRandomdelete(randomId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    removeImg(index) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.imgUrl.splice(index, 1);
          this.randomUrl = this.imgUrl;
          this.form.randomUrl = this.imgUrl;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getRowId(row) {
      this.extracItem = row;
      this.form.extractItem = row.extractItem;
    }
  },
  filters: {
    dateTime(val) {
      if (val) {
        return val.substr(0, 10);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-table .warning-row {
  background: oldlace;
}
::v-deep .el-table .denger-row {
  background: #ffe4e1;
}
::v-deep .el-upload {
  text-align: left;
}
::v-deep .el-image {
  margin-right: 10px;
  margin-top: 10px;
}
::v-deep .el-upload-list {
  display: flex;
  flex-wrap: wrap;
}
::v-deep .el-upload-list__item {
  width: 50%;
}
.bigfont {
  font-size: 19px;
  font-weight: 100;
  text-align: center;
  font-family: FangSong;
}
.small {
  text-align: center;
  font-weight: 100;
  font-size: 16px;
}
.fontitem1 {
  vertical-align: top;
  font-size: 16px;
  font-weight: 100;
}
.fontitem12 {
  font-size: 16px;
}
.topfont {
  font-size: 16px;
  font-weight: 400;
}
.input {
  font-size: 18px;
  font-weight: 400;
}
.small1 {
  text-align: center;
  font-weight: 100;
  font-size: 20px;
}
.zhong {
  font-size: 16px;
  padding-left: 10px;
}
.title {
  margin-bottom: 30px;
  font-size: 24px;
  font-family: SimSun;
}
.project-name {
  font-family: FangSong;
}
.project-name-1 {
  font-family: FangSong;
}
.topfont-name {
  font-family: FangSong;
}
.font-family {
  font-family: FangSong;
}
.ceshi {
  width: 100%;
  height: 20px;
  text-align: left;
  line-height: 20px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding-left: 9px;
  color: #ff0000;
  font-size: 12px;
}
.printTable {
  border: unset;
}
.noBorder {
  border: unset;
}
.rightBorder {
  border-right: 1px solid #9a9a9a;
}
.bottomBorder {
  border-bottom: 1px solid #9a9a9a;
}
.image-wrap {
  display: flex;
  flex-wrap: wrap;
}
.uploadimg-wrap {
  position: relative;
  margin-right: 10px;
  .icon {
    cursor: pointer;
    position: absolute;
    top: -1px;
    right: 3px;
    font-size: 16px;
    color: red;
  }
}
.unitSort-box li {
  margin-top: 5px;
}
.form-img-out {
  width: 130px;
  height: 130px;
}
.form-img-line {
  width: 500px;
  height: 500px;
}
.form-dialog {
  text-align: center;
}
.custom-input {
  ::v-deep .el-input__inner {
    cursor: pointer;
  }
  
}
</style>
